package com.tanhua.dubbo.api;

import com.tanhua.model.db.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Visitors visitors) {
        Criteria criteria = Criteria.where("visitorUserId").is(visitors.getVisitorUserId())
                .and("userId").is(visitors.getUserId())
                .and("visitDate").is(visitors.getVisitDate());
        boolean exists = mongoTemplate.exists(Query.query(criteria), Visitors.class);
        if (!exists) {
            mongoTemplate.save(visitors);
        }
    }

    @Override
    public List<Visitors> findByUserId(long userId, Long time) {
        Criteria criteria = Criteria.where("userId").is(userId).and("date").gt(time);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("date"))).limit(5);
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        return visitorsList;
    }

    @Override
    public List<Visitors> findFriends(long userId, int page, int pageSize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("date")))
                .skip((page - 1) * pageSize)
                .limit(pageSize);
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        return visitorsList;
    }

    @Override
    public List<Visitors> findFriendsByUserId(Integer page, Integer pagesize, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("date")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);

        return visitorsList;
    }

}